package com.lianyu.wangyiyun.fragment;

import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.palette.graphics.Palette;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.activity.PlayerActivity;
import com.lianyu.wangyiyun.databinding.FragmentCoverBinding;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.widget.musiceffect.view.EffectView;

import java.io.File;
import java.util.List;

/**
 * @author Chen Yuguang
 * @date 2021/5/9 16:45
 */
public class CoverFragment extends AbstractLazyFragment {

    /**
     * 旋转动画
     */
    private ObjectAnimator objectAnimator;

    /**
     * 音乐动效视图
     */
    private EffectView effectView;

    public EffectView getEffectView() {
        return effectView;
    }

    @Override
    protected View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        FragmentCoverBinding fragmentCoverBinding = FragmentCoverBinding.inflate(inflater, container, false);
        PlayerActivity playerActivity = (PlayerActivity) getActivity();
        fragmentCoverBinding.getRoot().setOnClickListener(v -> {
            if (playerActivity != null) {
                playerActivity.switchPager();
            }
        });
        //旋转动画
        objectAnimator = ObjectAnimator.ofFloat(fragmentCoverBinding.circleImage, "rotation", 0, 360);
        objectAnimator.setDuration(50000);
        //动画的反复次数
        objectAnimator.setRepeatCount(-1);
        //匀速插值器
        objectAnimator.setInterpolator(new LinearInterpolator());
        //处于播放状态开启旋转动画
        Bundle bundle = getArguments();
        if (bundle != null) {
            boolean isPlaying = bundle.getBoolean("isPlaying");
            if (isPlaying) {
                objectAnimator.start();
            }
        }
        effectView = fragmentCoverBinding.effectView;
        if (playerActivity != null) {
            MusicListViewModel mainMusicListViewModel = new ViewModelProvider(playerActivity, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
            mainMusicListViewModel.getPositionLiveData().observe(this, position -> {
                if (playerActivity.isPlaying()) {
                    objectAnimator.start();
                }
                List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
                if (mp3Infos != null) {
                    Mp3Info mp3Info = mp3Infos.get(position);
                    String url = mp3Info.getUrl();
                    String http = "http";
                    if (new File(url).isFile()) {
                        Bitmap albumPicture = null;
                        //取本地专辑图
                        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                        mediaMetadataRetriever.setDataSource(url);
                        byte[] data = mediaMetadataRetriever.getEmbeddedPicture();
                        if (data != null) {
                            //获取bitmap对象
                            albumPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
                        }
                        if (albumPicture != null) {
                            //设置本地专辑图为封面
                            fragmentCoverBinding.circleImage.setImageBitmap(albumPicture);
                            Palette.PaletteAsyncListener listener = palette -> {
                                if (palette != null) {
                                    int mutedLight = palette.getLightMutedColor(0x000000);
                                    fragmentCoverBinding.effectView.setColor(mutedLight);
                                }
                            };
                            Palette.from(albumPicture).generate(listener);
                        } else {
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cover);
                            Palette.PaletteAsyncListener listener = palette -> {
                                if (palette != null) {
                                    int mutedLight = palette.getLightMutedColor(0x000000);
                                    fragmentCoverBinding.effectView.setColor(mutedLight);
                                }
                            };
                            Palette.from(bitmap).generate(listener);
                            //设置默认封面
                            fragmentCoverBinding.circleImage.setImageBitmap(bitmap);
                        }
                    } else if (url.startsWith(http)) {
                        String album = mp3Info.getAlbum();
                        //设置网络专辑图为背景
                        Glide.with(this).asBitmap().load(album).placeholder(R.drawable.cover).into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                                Palette.PaletteAsyncListener listener = palette -> {
                                    if (palette != null) {
                                        int mutedLight = palette.getLightMutedColor(0x000000);
                                        fragmentCoverBinding.effectView.setColor(mutedLight);
                                    }
                                };
                                Palette.from(bitmap).generate(listener);
                                fragmentCoverBinding.circleImage.setImageBitmap(bitmap);
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }
                        });
                    } else {
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cover);
                        Palette.PaletteAsyncListener listener = palette -> {
                            if (palette != null) {
                                int mutedLight = palette.getLightMutedColor(0x000000);
                                fragmentCoverBinding.effectView.setColor(mutedLight);
                            }
                        };
                        Palette.from(bitmap).generate(listener);
                        //设置默认封面
                        fragmentCoverBinding.circleImage.setImageBitmap(bitmap);
                    }
                }
            });
        }

        return fragmentCoverBinding.getRoot();
    }

    public static CoverFragment newInstance(boolean isPlaying) {
        CoverFragment coverFragment = new CoverFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isPlaying", isPlaying);
        coverFragment.setArguments(bundle);
        return coverFragment;
    }

    /**
     * 暂停旋转动画
     */
    public void pauseAnimator() {
        if (objectAnimator != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                objectAnimator.pause();
            } else {
                objectAnimator.cancel();
            }
        }
    }

    /**
     * 继续旋转动画
     */
    public void continueAnimator() {
        if (objectAnimator != null) {
            if (objectAnimator.isStarted()) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    objectAnimator.resume();
                } else {
                    objectAnimator.start();
                }
            } else {
                objectAnimator.start();
            }
        }
    }

}
